package com.cencat.merchant.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cencat.common.response.ApiResponse;
import com.cencat.merchant.dto.RouteCreateDTO;
import com.cencat.merchant.dto.RouteQueryDTO;
import com.cencat.merchant.dto.RouteUpdateDTO;
import com.cencat.merchant.entity.Route;
import com.cencat.merchant.service.RouteService;
import com.cencat.merchant.vo.RouteVO;
import com.cencat.merchant.vo.RouteStatisticsVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 路线管理控制器
 * 提供路线的增删改查、统计等功能
 * 
 * @author cencat
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/api/merchant/route")
@Tag(name = "路线管理", description = "商家路线管理相关接口")
@Slf4j
public class RouteController {

    @Autowired
    private RouteService routeService;

    /**
     * 创建路线
     * 
     * @param createDTO 路线创建DTO
     * @return 创建结果
     */
    @PostMapping
    @Operation(summary = "创建路线", description = "创建新的配送路线")
    public ApiResponse<RouteVO> createRoute(@Valid @RequestBody RouteCreateDTO createDTO) {
        log.info("创建路线，参数：{}", createDTO);
        try {
            RouteVO routeVO = routeService.createRoute(createDTO);
            log.info("路线创建成功，ID：{}", routeVO.getId());
            return ApiResponse.success(routeVO);
        } catch (Exception e) {
            log.error("创建路线失败", e);
            return ApiResponse.error("创建路线失败：" + e.getMessage());
        }
    }

    /**
     * 更新路线信息
     * 
     * @param id 路线ID
     * @param updateDTO 路线更新DTO
     * @return 更新结果
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新路线", description = "更新路线信息")
    public ApiResponse<RouteVO> updateRoute(
            @Parameter(description = "路线ID") @PathVariable @NotNull @Min(1) Long id,
            @Valid @RequestBody RouteUpdateDTO updateDTO) {
        log.info("更新路线，ID：{}，参数：{}", id, updateDTO);
        try {
            RouteVO routeVO = routeService.updateRoute(id, updateDTO);
            log.info("路线更新成功，ID：{}", id);
            return ApiResponse.success(routeVO);
        } catch (Exception e) {
            log.error("更新路线失败，ID：{}", id, e);
            return ApiResponse.error("更新路线失败：" + e.getMessage());
        }
    }

    /**
     * 删除路线
     * 
     * @param id 路线ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除路线", description = "删除指定路线")
    public ApiResponse<Void> deleteRoute(
            @Parameter(description = "路线ID") @PathVariable @NotNull @Min(1) Long id) {
        log.info("删除路线，ID：{}", id);
        try {
            routeService.deleteRoute(id);
            log.info("路线删除成功，ID：{}", id);
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("删除路线失败，ID：{}", id, e);
            return ApiResponse.error("删除路线失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询路线详情
     * 
     * @param id 路线ID
     * @return 路线详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询路线详情", description = "根据ID查询路线详细信息")
    public ApiResponse<RouteVO> getRouteById(
            @Parameter(description = "路线ID") @PathVariable @NotNull @Min(1) Long id) {
        log.info("查询路线详情，ID：{}", id);
        try {
            RouteVO routeVO = routeService.getRouteById(id);
            return ApiResponse.success(routeVO);
        } catch (Exception e) {
            log.error("查询路线详情失败，ID：{}", id, e);
            return ApiResponse.error("查询路线详情失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询路线列表
     * 
     * @param queryDTO 查询条件
     * @return 路线分页列表
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询路线", description = "根据条件分页查询路线列表")
    public ApiResponse<IPage<RouteVO>> getRoutesByPage(@Valid RouteQueryDTO queryDTO) {
        log.info("分页查询路线，参数：{}", queryDTO);
        try {
            IPage<RouteVO> pageResult = routeService.getRoutesByPage(queryDTO);
            return ApiResponse.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询路线失败", e);
            return ApiResponse.error("查询路线列表失败：" + e.getMessage());
        }
    }

    /**
     * 查询所有可用路线
     * 
     * @return 路线列表
     */
    @GetMapping("/available")
    @Operation(summary = "查询可用路线", description = "查询所有可用的路线")
    public ApiResponse<List<RouteVO>> getAvailableRoutes() {
        log.info("查询所有可用路线");
        try {
            List<RouteVO> routes = routeService.getAvailableRoutes();
            return ApiResponse.success(routes);
        } catch (Exception e) {
            log.error("查询可用路线失败", e);
            return ApiResponse.error("查询可用路线失败：" + e.getMessage());
        }
    }

    /**
     * 根据司机ID查询路线
     * 
     * @param driverId 司机ID
     * @return 路线列表
     */
    @GetMapping("/driver/{driverId}")
    @Operation(summary = "查询司机路线", description = "根据司机ID查询其负责的路线")
    public ApiResponse<List<RouteVO>> getRoutesByDriverId(
            @Parameter(description = "司机ID") @PathVariable @NotNull @Min(1) Long driverId) {
        log.info("查询司机路线，司机ID：{}", driverId);
        try {
            List<RouteVO> routes = routeService.getRoutesByDriverId(driverId);
            return ApiResponse.success(routes);
        } catch (Exception e) {
            log.error("查询司机路线失败，司机ID：{}", driverId, e);
            return ApiResponse.error("查询司机路线失败：" + e.getMessage());
        }
    }

    /**
     * 启用路线
     * 
     * @param id 路线ID
     * @return 操作结果
     */
    @PutMapping("/{id}/enable")
    @Operation(summary = "启用路线", description = "启用指定路线")
    public ApiResponse<Void> enableRoute(
            @Parameter(description = "路线ID") @PathVariable @NotNull @Min(1) Long id) {
        log.info("启用路线，ID：{}", id);
        try {
            routeService.enableRoute(id);
            log.info("路线启用成功，ID：{}", id);
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("启用路线失败，ID：{}", id, e);
            return ApiResponse.error("启用路线失败：" + e.getMessage());
        }
    }

    /**
     * 禁用路线
     * 
     * @param id 路线ID
     * @return 操作结果
     */
    @PutMapping("/{id}/disable")
    @Operation(summary = "禁用路线", description = "禁用指定路线")
    public ApiResponse<Void> disableRoute(
            @Parameter(description = "路线ID") @PathVariable @NotNull @Min(1) Long id) {
        log.info("禁用路线，ID：{}", id);
        try {
            routeService.disableRoute(id);
            log.info("路线禁用成功，ID：{}", id);
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("禁用路线失败，ID：{}", id, e);
            return ApiResponse.error("禁用路线失败：" + e.getMessage());
        }
    }

    /**
     * 获取路线统计信息
     * 
     * @return 统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "路线统计", description = "获取路线相关统计信息")
    public ApiResponse<RouteStatisticsVO> getRouteStatistics() {
        log.info("获取路线统计信息");
        try {
            RouteStatisticsVO statistics = routeService.getRouteStatistics();
            return ApiResponse.success(statistics);
        } catch (Exception e) {
            log.error("获取路线统计信息失败", e);
            return ApiResponse.error("获取统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除路线
     * 
     * @param ids 路线ID列表
     * @return 删除结果
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除路线", description = "批量删除指定的路线")
    public ApiResponse<Void> batchDeleteRoutes(@RequestBody List<Long> ids) {
        log.info("批量删除路线，IDs：{}", ids);
        try {
            routeService.batchDeleteRoutes(ids);
            log.info("批量删除路线成功，数量：{}", ids.size());
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("批量删除路线失败", e);
            return ApiResponse.error("批量删除路线失败：" + e.getMessage());
        }
    }
}